<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mermaid 架构图交互演示</title>
    <script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            margin: 0;
            padding: 20px;
            background: #f5f7fa;
        }
        
        .demo-header {
            text-align: center;
            margin-bottom: 30px;
        }
        
        .demo-container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .toolbar {
            background: #2c3e50;
            color: white;
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .toolbar button {
            background: #3498db;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            margin-left: 10px;
        }
        
        .toolbar button:hover {
            background: #2980b9;
        }
        
        #mermaid-container {
            position: relative;
            padding: 30px;
            min-height: 500px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        .node-tooltip {
            position: absolute;
            background: rgba(0, 0, 0, 0.9);
            color: white;
            padding: 12px;
            border-radius: 8px;
            font-size: 13px;
            pointer-events: none;
            z-index: 1000;
            display: none;
            max-width: 250px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.3);
        }
        
        .node-status-indicator {
            position: absolute;
            width: 16px;
            height: 16px;
            border-radius: 50%;
            border: 3px solid white;
            z-index: 100;
            box-shadow: 0 2px 8px rgba(0,0,0,0.2);
        }
        
        .status-healthy { background: #27ae60; }
        .status-warning { background: #f39c12; }
        .status-error { background: #e74c3c; }
        .status-maintenance { background: #9b59b6; }
        
        .capability-panel {
            position: absolute;
            background: white;
            border: 2px solid #3498db;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
            z-index: 1001;
            display: none;
            min-width: 280px;
            max-width: 400px;
        }
        
        .capability-panel h4 {
            margin: 0 0 15px 0;
            color: #2c3e50;
            font-size: 18px;
            border-bottom: 2px solid #ecf0f1;
            padding-bottom: 8px;
        }
        
        .node-metrics {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 6px;
            margin-bottom: 15px;
            font-size: 12px;
        }
        
        .capability-item {
            padding: 10px 15px;
            margin: 6px 0;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .capability-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.2);
        }
        
        .capability-item .icon {
            font-size: 16px;
            margin-right: 8px;
        }
        
        .panel-footer {
            margin-top: 15px;
            text-align: right;
        }
        
        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 13px;
            transition: all 0.2s ease;
        }
        
        .btn-primary {
            background: #3498db;
            color: white;
        }
        
        .btn-primary:hover {
            background: #2980b9;
        }
        
        .btn-secondary {
            background: #95a5a6;
            color: white;
            margin-left: 8px;
        }
        
        .btn-secondary:hover {
            background: #7f8c8d;
        }
        
        .execution-result {
            position: fixed;
            top: 20px;
            right: 20px;
            background: white;
            border-left: 4px solid #27ae60;
            padding: 15px 20px;
            border-radius: 8px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            z-index: 2000;
            display: none;
            max-width: 400px;
        }
        
        .execution-result.error {
            border-left-color: #e74c3c;
        }
        
        .execution-result.warning {
            border-left-color: #f39c12;
        }
        
        .loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255,255,255,0.8);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1500;
        }
        
        .spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px) scale(0.9); }
            to { opacity: 1; transform: translateY(0) scale(1); }
        }
        
        .node-enhanced {
            cursor: pointer !important;
        }
        
        .node-highlighted {
            filter: drop-shadow(0 0 8px #3498db);
        }
        
        @media (max-width: 768px) {
            .demo-container {
                margin: 10px;
                border-radius: 8px;
            }
            
            .capability-panel {
                max-width: 90vw;
                left: 5vw !important;
                right: 5vw !important;
            }
        }
    </style>
</head>
<body>
    <div class="demo-header">
        <h1>🎯 Mermaid 架构图交互演示</h1>
        <p>点击节点查看功能，体验完整的架构图交互</p>
    </div>
    
    <div class="demo-container">
        <div class="toolbar">
            <div>
                <span>🔄 实时架构监控</span>
                <span id="last-update"></span>
            </div>
            <div>
                <button onclick="refreshDiagram()">🔄 刷新</button>
                <button onclick="toggleFullscreen()">🔍 全屏</button>
                <button onclick="exportDiagram()">💾 导出</button>
            </div>
        </div>
        
        <div id="mermaid-container">
            <div id="mermaid-diagram"></div>
            <div class="loading-overlay" id="loading-overlay">
                <div class="spinner"></div>
            </div>
        </div>
    </div>
    
    <!-- 工具提示 -->
    <div id="node-tooltip" class="node-tooltip"></div>
    
    <!-- 能力面板 -->
    <div id="capability-panel" class="capability-panel">
        <h4 id="panel-title">节点功能</h4>
        <div id="panel-metrics" class="node-metrics"></div>
        <div id="capability-list"></div>
        <div class="panel-footer">
            <button class="btn btn-primary" onclick="refreshNodeStatus()">🔄 刷新状态</button>
            <button class="btn btn-secondary" onclick="hideCapabilityPanel()">✖️ 关闭</button>
        </div>
    </div>
    
    <!-- 执行结果通知 -->
    <div id="execution-result" class="execution-result">
        <div id="result-content"></div>
        <button style="float: right; margin-top: 10px;" class="btn btn-secondary" onclick="hideExecutionResult()">关闭</button>
    </div>

    <script>
        // 初始化Mermaid
        mermaid.initialize({ 
            startOnLoad: false,
            theme: 'default',
            flowchart: {
                useMaxWidth: true,
                htmlLabels: true
            }
        });
        
        const mermaidDefinition = `
        graph TB
            api["🌐 API Gateway<br/>网关服务"]
            user["👥 User Service<br/>用户服务"] 
            order["📦 Order Service<br/>订单服务"]
            payment["💳 Payment Service<br/>支付服务"]
            db["🗄️ Database<br/>数据库"]
            cache["⚡ Redis Cache<br/>缓存服务"]
            
            api --> user
            api --> order
            api --> payment
            user --> db
            order --> db
            payment --> db
            user --> cache
            order --> cache
            
            classDef gateway fill:#3498db,stroke:#2980b9,stroke-width:3px,color:#fff
            classDef service fill:#2ecc71,stroke:#27ae60,stroke-width:2px,color:#fff
            classDef storage fill:#e67e22,stroke:#d35400,stroke-width:2px,color:#fff
            
            class api gateway
            class user,order,payment service
            class db,cache storage
        `;
        
        // 节点配置数据
        const nodeConfig = {
            'api': {
                name: '🌐 API Gateway',
                status: 'healthy',
                type: 'gateway',
                capabilities: [
                    { id: 'health_check', name: '健康检查', icon: '❤️', timeout: 30 },
                    { id: 'view_logs', name: '查看日志', icon: '📋', timeout: 15 },
                    { id: 'performance', name: '性能监控', icon: '📊', timeout: 20 }
                ],
                metrics: {
                    'CPU使用率': '23%',
                    '内存使用': '512MB',
                    '请求/分钟': '1,234',
                    '响应时间': '15ms'
                },
                description: '系统入口网关，负责路由和负载均衡'
            },
            'user': {
                name: '👥 User Service',
                status: 'warning', 
                type: 'service',
                capabilities: [
                    { id: 'user_count', name: '用户统计', icon: '👥', timeout: 20 },
                    { id: 'user_activity', name: '活跃度分析', icon: '📈', timeout: 25 },
                    { id: 'user_cleanup', name: '数据清理', icon: '🧹', timeout: 60 }
                ],
                metrics: {
                    'CPU使用率': '67%',
                    '内存使用': '1.1GB',
                    '活跃连接': '456',
                    '注册用户': '15,623'
                },
                description: '用户管理服务，处理用户注册登录等功能'
            },
            'order': {
                name: '📦 Order Service',
                status: 'healthy',
                type: 'service',
                capabilities: [
                    { id: 'order_count', name: '订单统计', icon: '📊', timeout: 20 },
                    { id: 'order_report', name: '交易报告', icon: '📈', timeout: 30 },
                    { id: 'order_sync', name: '数据同步', icon: '🔄', timeout: 45 }
                ],
                metrics: {
                    'CPU使用率': '34%',
                    '内存使用': '896MB',
                    '订单/小时': '156',
                    '处理中订单': '23'
                },
                description: '订单处理服务，管理订单生命周期'
            },
            'payment': {
                name: '💳 Payment Service',
                status: 'healthy',
                type: 'service',
                capabilities: [
                    { id: 'payment_status', name: '支付状态', icon: '💰', timeout: 15 },
                    { id: 'payment_report', name: '收入报告', icon: '📊', timeout: 25 },
                    { id: 'payment_reconcile', name: '对账处理', icon: '🔍', timeout: 120 }
                ],
                metrics: {
                    'CPU使用率': '12%',
                    '内存使用': '445MB',
                    '支付成功率': '98.5%',
                    '今日交易': '¥234,567'
                },
                description: '支付处理服务，处理各种支付方式'
            },
            'db': {
                name: '🗄️ Database',
                status: 'error',
                type: 'storage',
                capabilities: [
                    { id: 'db_status', name: '连接检查', icon: '🔍', timeout: 10 },
                    { id: 'db_performance', name: '性能分析', icon: '⚡', timeout: 30 },
                    { id: 'db_backup', name: '数据备份', icon: '💾', timeout: 300 }
                ],
                metrics: {
                    'CPU使用率': '89%',
                    '内存使用': '2.3GB',
                    '连接数': '78/100',
                    '查询/秒': '1,456'
                },
                description: '主数据库，存储核心业务数据'
            },
            'cache': {
                name: '⚡ Redis Cache',
                status: 'healthy',
                type: 'storage',
                capabilities: [
                    { id: 'cache_status', name: '缓存状态', icon: '⚡', timeout: 5 },
                    { id: 'cache_stats', name: '命中统计', icon: '🎯', timeout: 10 },
                    { id: 'cache_clear', name: '清理缓存', icon: '🧹', timeout: 15 }
                ],
                metrics: {
                    'CPU使用率': '8%',
                    '内存使用': '1.2GB',
                    '命中率': '96.8%',
                    '键数量': '156,789'
                },
                description: 'Redis缓存服务，提升系统响应速度'
            }
        };
        
        let nodeAreas = [];
        let currentSelectedNode = null;
        let statusUpdateInterval = null;
        
        // 渲染Mermaid图表
        async function renderMermaidDiagram() {
            showLoading(true);
            
            try {
                const { svg } = await mermaid.render('mermaid-graph', mermaidDefinition);
                document.getElementById('mermaid-diagram').innerHTML = svg;
                
                // 渲染完成后增强交互
                setTimeout(() => {
                    enhanceMermaidInteraction();
                    updateLastUpdateTime();
                    showLoading(false);
                }, 500);
                
            } catch (error) {
                console.error('Mermaid渲染失败:', error);
                showNotification('图表渲染失败: ' + error.message, 'error');
                showLoading(false);
            }
        }
        
        // 增强Mermaid交互功能
        function enhanceMermaidInteraction() {
            const svgElement = document.querySelector('#mermaid-diagram svg');
            const container = document.getElementById('mermaid-container');
            
            if (!svgElement) {
                console.log('未找到SVG元素');
                return;
            }
            
            console.log('开始增强Mermaid交互...');
            
            // 尝试多种方式获取节点元素
            let nodeElements = svgElement.querySelectorAll('.node');
            if (nodeElements.length === 0) {
                nodeElements = svgElement.querySelectorAll('g[class*="node"]');
            }
            if (nodeElements.length === 0) {
                nodeElements = svgElement.querySelectorAll('g');
            }
            
            console.log(`找到 ${nodeElements.length} 个潜在节点元素`);
            
            nodeElements.forEach((nodeElement, index) => {
                // 检查是否包含文本和图形
                const textElement = nodeElement.querySelector('text');
                const rectElement = nodeElement.querySelector('rect, polygon, path');
                
                if (textElement && rectElement) {
                    const nodeId = extractNodeId(nodeElement, index);
                    const nodeData = nodeConfig[nodeId];
                    
                    console.log(`处理节点 ${index}: ${nodeId}`, textElement.textContent);
                    
                    if (nodeData) {
                        // 添加CSS类便于样式控制
                        nodeElement.classList.add('node-enhanced');
                        
                        // 添加点击事件
                        addNodeClickEvent(nodeElement, nodeId, nodeData);
                        
                        // 添加悬停事件
                        addNodeHoverEvent(nodeElement, nodeData);
                        
                        // 添加状态指示器
                        addStatusIndicator(container, nodeElement, nodeData);
                        
                        // 存储节点信息
                        nodeAreas.push({
                            element: nodeElement,
                            nodeId: nodeId,
                            config: nodeData
                        });
                    }
                }
            });
            
            console.log(`成功处理了 ${nodeAreas.length} 个节点`);
        }
        
        // 提取节点ID
        function extractNodeId(nodeElement, fallbackIndex) {
            // 先尝试从元素的class或id属性获取
            if (nodeElement.id) {
                const id = nodeElement.id.toLowerCase();
                if (id.includes('api')) return 'api';
                if (id.includes('user')) return 'user';
                if (id.includes('order')) return 'order';
                if (id.includes('payment')) return 'payment';
                if (id.includes('db') || id.includes('database')) return 'db';
                if (id.includes('cache') || id.includes('redis')) return 'cache';
            }
            
            // 然后尝试从文本内容匹配
            const textElements = nodeElement.querySelectorAll('text');
            for (let textEl of textElements) {
                const text = textEl.textContent.trim();
                console.log('检查文本:', text);
                
                if (text.includes('API Gateway') || text.includes('🌐') || text.includes('网关')) return 'api';
                if (text.includes('User Service') || text.includes('👥') || text.includes('用户')) return 'user';
                if (text.includes('Order Service') || text.includes('📦') || text.includes('订单')) return 'order';
                if (text.includes('Payment Service') || text.includes('💳') || text.includes('支付')) return 'payment';
                if (text.includes('Database') || text.includes('🗄️') || text.includes('数据库')) return 'db';
                if (text.includes('Redis') || text.includes('⚡') || text.includes('缓存')) return 'cache';
            }
            
            return `node${fallbackIndex}`;
        }
        
        // 添加节点点击事件
        function addNodeClickEvent(nodeElement, nodeId, nodeData) {
            nodeElement.style.cursor = 'pointer';
            
            nodeElement.addEventListener('click', (event) => {
                event.stopPropagation();
                
                console.log(`点击了节点: ${nodeId}`, nodeData);
                
                // 高亮选中的节点
                highlightNode(nodeElement);
                currentSelectedNode = nodeId;
                
                // 在节点旁边显示快速选项
                showQuickOptions(event, nodeElement, nodeId, nodeData);
            });
        }
        
        // 添加节点悬停事件
        function addNodeHoverEvent(nodeElement, nodeData) {
            const tooltip = document.getElementById('node-tooltip');
            
            nodeElement.addEventListener('mouseenter', (event) => {
                const statusText = getStatusText(nodeData.status);
                const statusIcon = getStatusIcon(nodeData.status);
                
                tooltip.innerHTML = `
                    <div style="font-weight: bold; margin-bottom: 8px;">
                        ${nodeData.name}
                    </div>
                    <div style="margin-bottom: 6px;">
                        ${statusIcon} 状态: ${statusText}
                    </div>
                    <div style="font-size: 12px; opacity: 0.9;">
                        ${nodeData.description}
                    </div>
                    <div style="margin-top: 8px; font-size: 11px; opacity: 0.7;">
                        点击查看详细功能
                    </div>
                `;
                tooltip.style.display = 'block';
                updateTooltipPosition(event, tooltip);
            });
            
            nodeElement.addEventListener('mousemove', (event) => {
                updateTooltipPosition(event, tooltip);
            });
            
            nodeElement.addEventListener('mouseleave', () => {
                tooltip.style.display = 'none';
            });
        }
        
        // 添加状态指示器
        function addStatusIndicator(container, nodeElement, nodeData) {
            const rect = nodeElement.getBoundingClientRect();
            const containerRect = container.getBoundingClientRect();
            
            const indicator = document.createElement('div');
            indicator.className = `node-status-indicator status-${nodeData.status}`;
            indicator.style.left = (rect.right - containerRect.left - 8) + 'px';
            indicator.style.top = (rect.top - containerRect.top - 8) + 'px';
            indicator.title = `状态: ${getStatusText(nodeData.status)}`;
            
            container.appendChild(indicator);
        }
        
        // 在节点旁边显示快速选项
        function showQuickOptions(event, nodeElement, nodeId, nodeData) {
            // 先移除已存在的快速选项
            removeExistingQuickOptions();
            
            const rect = nodeElement.getBoundingClientRect();
            const container = document.getElementById('mermaid-container');
            const containerRect = container.getBoundingClientRect();
            
            // 创建快速选项容器
            const optionsContainer = document.createElement('div');
            optionsContainer.className = 'quick-options-container';
            optionsContainer.style.cssText = `
                position: absolute;
                left: ${rect.right - containerRect.left + 10}px;
                top: ${rect.top - containerRect.top}px;
                background: white;
                border: 2px solid #3498db;
                border-radius: 8px;
                box-shadow: 0 4px 15px rgba(0,0,0,0.2);
                z-index: 1000;
                min-width: 150px;
                animation: fadeIn 0.3s ease-out;
            `;
            
            // 添加标题
            const title = document.createElement('div');
            title.style.cssText = `
                padding: 10px 15px;
                background: #3498db;
                color: white;
                font-weight: bold;
                font-size: 14px;
                border-radius: 6px 6px 0 0;
            `;
            title.textContent = nodeData.name;
            optionsContainer.appendChild(title);
            
            // 添加选项
            const options = nodeData.capabilities.slice(0, 2); // 只显示前两个选项
            options.forEach(option => {
                const optionBtn = document.createElement('div');
                optionBtn.style.cssText = `
                    padding: 10px 15px;
                    cursor: pointer;
                    border-bottom: 1px solid #ecf0f1;
                    transition: background-color 0.2s;
                    display: flex;
                    align-items: center;
                    gap: 8px;
                `;
                optionBtn.innerHTML = `<span>${option.icon}</span><span>${option.name}</span>`;
                
                optionBtn.addEventListener('mouseenter', () => {
                    optionBtn.style.backgroundColor = '#f8f9fa';
                });
                optionBtn.addEventListener('mouseleave', () => {
                    optionBtn.style.backgroundColor = '';
                });
                optionBtn.addEventListener('click', () => {
                    executeQuickAction(nodeId, option);
                    removeExistingQuickOptions();
                });
                
                optionsContainer.appendChild(optionBtn);
            });
            
            // 添加关闭按钮
            const closeBtn = document.createElement('div');
            closeBtn.style.cssText = `
                padding: 8px 15px;
                text-align: center;
                background: #f8f9fa;
                color: #666;
                cursor: pointer;
                border-radius: 0 0 6px 6px;
                font-size: 12px;
            `;
            closeBtn.textContent = '关闭';
            closeBtn.addEventListener('click', removeExistingQuickOptions);
            optionsContainer.appendChild(closeBtn);
            
            container.appendChild(optionsContainer);
            
            // 3秒后自动关闭
            setTimeout(removeExistingQuickOptions, 3000);
        }
        
        // 移除已存在的快速选项
        function removeExistingQuickOptions() {
            const existing = document.querySelectorAll('.quick-options-container');
            existing.forEach(el => {
                if (el.parentNode) {
                    el.parentNode.removeChild(el);
                }
            });
        }
        
        // 执行快速操作
        function executeQuickAction(nodeId, action) {
            console.log(`执行快速操作: ${nodeId} -> ${action.name}`);
            
            // 显示执行中的提示
            showNotification(`⚡ 正在执行 ${action.name}...`, 'success');
            
            // 模拟执行时间
            setTimeout(() => {
                const mockResult = generateMockResult(nodeId, action);
                showNotification(`✅ ${action.name} 执行完成`, 'success');
                
                // 显示结果
                setTimeout(() => {
                    alert(`${action.name} 执行结果:\n\n${mockResult}`);
                }, 500);
            }, 1000);
        }
        
        // 生成模拟结果
        function generateMockResult(nodeId, action) {
            const results = {
                'api_health_check': '✅ API Gateway 健康检查通过\n响应时间: 15ms\nCPU: 23%\n内存: 512MB',
                'api_view_logs': '📋 最近10条日志:\n[INFO] 接收请求 GET /api/users\n[INFO] 转发到用户服务\n[INFO] 响应200 OK',
                'user_user_count': '👥 用户统计结果:\n总用户数: 15,623\n活跃用户: 8,947\n今日新增: 127',
                'user_user_activity': '📈 用户活跃度分析:\n日活跃率: 67%\n周活跃率: 89%\n月活跃率: 95%',
                'order_order_count': '📊 订单统计:\n今日订单: 234\n处理中: 12\n已完成: 222',
                'payment_payment_status': '💰 支付状态检查:\n成功率: 98.5%\n今日交易: ¥234,567\n异常订单: 3',
                'db_db_status': '🔍 数据库状态:\n连接数: 78/100\nQPS: 1,456\n响应时间: 3ms',
                'cache_cache_status': '⚡ 缓存状态:\n命中率: 96.8%\n内存使用: 1.2GB\n键数量: 156,789'
            };
            
            const key = `${nodeId}_${action.id}`;
            return results[key] || `${action.name} 执行成功\n节点: ${nodeId}\n时间: ${new Date().toLocaleTimeString()}`;
        }
        
        // 执行节点能力
        async function executeCapability(nodeId, capability) {
            console.log(`执行能力: ${nodeId} -> ${capability.name}`);
            
            showLoading(true);
            hideCapabilityPanel();
            
            try {
                const response = await fetch('/api/scripts/execute', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        nodeId: nodeId,
                        capabilityId: capability.id
                    })
                });
                
                const data = await response.json();
                
                if (response.ok && data.status === 'success') {
                    showNotification(`✅ ${capability.name} 执行成功`, 'success');
                    
                    // 显示详细结果
                    setTimeout(() => {
                        showExecutionResult(data);
                    }, 1000);
                } else {
                    throw new Error(data.error || '执行失败');
                }
                
            } catch (error) {
                console.error('执行失败:', error);
                showNotification(`❌ ${capability.name} 执行失败: ${error.message}`, 'error');
            } finally {
                showLoading(false);
            }
        }
        
        // 显示执行结果
        function showExecutionResult(data) {
            const resultDiv = document.getElementById('execution-result');
            const contentDiv = document.getElementById('result-content');
            
            contentDiv.innerHTML = `
                <h4>🎯 执行结果</h4>
                <div style="margin-bottom: 10px;">
                    <strong>节点:</strong> ${data.nodeId} | 
                    <strong>功能:</strong> ${data.capabilityId} |
                    <strong>耗时:</strong> ${data.duration}ms
                </div>
                <div style="background: #f8f9fa; padding: 12px; border-radius: 6px; white-space: pre-wrap; font-family: monospace; font-size: 12px; max-height: 200px; overflow-y: auto;">
                    ${data.output}
                </div>
            `;
            
            resultDiv.style.display = 'block';
            
            // 5秒后自动隐藏
            setTimeout(() => {
                hideExecutionResult();
            }, 5000);
        }
        
        // 工具函数
        function highlightNode(nodeElement) {
            // 移除其他节点的高亮
            nodeAreas.forEach(area => {
                area.element.classList.remove('node-highlighted');
            });
            
            // 高亮当前节点
            nodeElement.classList.add('node-highlighted');
        }
        
        function updateTooltipPosition(event, tooltip) {
            const x = Math.min(event.pageX + 15, window.innerWidth - 270);
            const y = Math.max(event.pageY - 80, 10);
            
            tooltip.style.left = x + 'px';
            tooltip.style.top = y + 'px';
        }
        
        function getStatusText(status) {
            const statusMap = {
                'healthy': '正常',
                'warning': '警告', 
                'error': '错误',
                'maintenance': '维护中'
            };
            return statusMap[status] || '未知';
        }
        
        function getStatusIcon(status) {
            const iconMap = {
                'healthy': '✅',
                'warning': '⚠️',
                'error': '❌',
                'maintenance': '🔧'
            };
            return iconMap[status] || '❓';
        }
        
        function showLoading(show) {
            document.getElementById('loading-overlay').style.display = show ? 'flex' : 'none';
        }
        
        function showNotification(message, type = 'success') {
            // 简单的通知，这里可以用更复杂的通知库
            const notification = document.createElement('div');
            notification.style.cssText = `
                position: fixed;
                top: 20px;
                left: 50%;
                transform: translateX(-50%);
                background: ${type === 'error' ? '#e74c3c' : type === 'warning' ? '#f39c12' : '#27ae60'};
                color: white;
                padding: 12px 20px;
                border-radius: 8px;
                box-shadow: 0 4px 15px rgba(0,0,0,0.2);
                z-index: 3000;
                font-weight: bold;
            `;
            notification.textContent = message;
            document.body.appendChild(notification);
            
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.parentNode.removeChild(notification);
                }
            }, 3000);
        }
        
        function hideCapabilityPanel() {
            document.getElementById('capability-panel').style.display = 'none';
        }
        
        function hideExecutionResult() {
            document.getElementById('execution-result').style.display = 'none';
        }
        
        function updateLastUpdateTime() {
            const now = new Date().toLocaleTimeString('zh-CN');
            document.getElementById('last-update').textContent = `最后更新: ${now}`;
        }
        
        // 工具栏功能
        function refreshDiagram() {
            showNotification('🔄 正在刷新架构图...', 'success');
            renderMermaidDiagram();
        }
        
        function refreshNodeStatus() {
            if (currentSelectedNode) {
                showNotification('🔄 正在刷新节点状态...', 'success');
                hideCapabilityPanel();
            }
        }
        
        function toggleFullscreen() {
            const container = document.querySelector('.demo-container');
            if (!document.fullscreenElement) {
                container.requestFullscreen().catch(err => {
                    console.error('全屏模式失败:', err);
                });
            } else {
                document.exitFullscreen();
            }
        }
        
        function exportDiagram() {
            const svgElement = document.querySelector('#mermaid-diagram svg');
            if (svgElement) {
                const svgData = new XMLSerializer().serializeToString(svgElement);
                const svgBlob = new Blob([svgData], {type: 'image/svg+xml;charset=utf-8'});
                const svgUrl = URL.createObjectURL(svgBlob);
                
                const downloadLink = document.createElement('a');
                downloadLink.href = svgUrl;
                downloadLink.download = 'architecture-diagram.svg';
                document.body.appendChild(downloadLink);
                downloadLink.click();
                document.body.removeChild(downloadLink);
                
                showNotification('💾 架构图已导出', 'success');
            }
        }
        
        // 点击空白区域隐藏面板
        document.addEventListener('click', (event) => {
            if (!event.target.closest('#capability-panel') && 
                !event.target.closest('.node-enhanced') &&
                !event.target.closest('.quick-options-container')) {
                hideCapabilityPanel();
                removeExistingQuickOptions();
            }
        });
        
        // 键盘快捷键
        document.addEventListener('keydown', (event) => {
            if (event.key === 'Escape') {
                hideCapabilityPanel();
                hideExecutionResult();
            } else if (event.key === 'F5' || (event.ctrlKey && event.key === 'r')) {
                event.preventDefault();
                refreshDiagram();
            }
        });
        
        // 初始化
        document.addEventListener('DOMContentLoaded', () => {
            renderMermaidDiagram();
            
            // 定期更新时间
            setInterval(updateLastUpdateTime, 30000);
        });
    </script>
</body>
</html>